﻿layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;
    var Updload = localStorage.getItem("UploadID");
    // 事件
    util.on('lay-on', {
        'test-page-new': function () {
            let selectedRows = [];
            // 创建弹出层
            var index = layer.open({
                type: 1,
                title: '产品信息',
                area: ['1100px', '500px'], // 宽高
                content: '<form class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px">产品编码:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="productsCode" placeholder="产品编码" style="width:200px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px">产品名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="B" placeholder="产品名称" id="productsName" style="width:200px;" lay-affix="clear" class="layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchBtn">查询</button>' +
                    '</div> ' +
                    '</form>' +
                    '<table class="layui-table" lay-filter="Produrement-Id" id="Produrement-Id">' +
                    '<thead>' +
                    '<tr>' +
                    '<th lay-data="{checkbox:true}" rowspan="2"></th>' +
                    '<col width="150">' +
                    '<col>' +
                    '</tr>' +
                    '</thead>' +
                    '</table>' +
                    '<button type="button" style="margin-top: 20px;margin-left: 500px;" id="demo-login"  class="layui-btn layui-bg-blue">提交</button>'
            });
            form.render();

            // 弹出层弹出时显示数据
            getProcurementList({
                productsCode: null,
                productsName: null,
                pageIndex: 1,
                pageSize: 4
            });

            // 查询
            $("#searchBtn").on('click', function () {
                var productsCode = $("#productsCode").val();
                var productsName = $("#productsName").val();

                getProcurementList({
                    productsCode: productsCode,
                    productsName: productsName,
                    pageIndex: 1,
                    pageSize: 4
                });
            });

            // 调用入库产品显示方法
            function getProcurementList({ productsCode, productsName, pageIndex, pageSize }) {
                $.ajax({
                    url: '/EnterStorage/EnterStorageSelect',
                    type: 'get',
                    toolbar: '#toolbarDemo',
                    data: {
                        StockCode: null,
                        StockOrderType: null,
                        StateSP: null,
                        productsCode: productsCode,
                        productsName: productsName,
                        pageIndex: pageIndex,
                        pageSize: pageSize,
                        Token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        var data = JSON.parse(res);
                        table.render({
                            elem: '#Produrement-Id',
                            totalRow: true, // 开启合计行
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'productsCode', width: 120, title: '产品编码' },
                                { field: 'productsName', width: 120, title: '产品名称' },
                                { field: 'specs', width: 120, title: '规格' },
                                { field: 'productTypeName', width: 120, title: '类别' },
                                { field: 'specs', width: 120, title: '存储单位' },
                                {
                                    width: 120, title: '包装类型', templet: function (d) {
                                        return '1'
                                    }
                                },
                                { field: 'sprice', width: 120, title: '单价' },
                                {
                                    width: 120, title: '重量', templet: function (d) {
                                        return '0'
                                    }
                                },
                                { width: 120, title: '显示名' },
                            ]],
                            data: data.data.list,//数据源
                            page: true,   // 启用分
                            limit: 5,    // 每页显示多少条数据
                            limits: [10, 20, 30],  // 分页选择项
                            curr: 1,  // 当前页
                            total: data.data.sumcount,  // 总记录数
                            loading: true, // 启用加载状态
                            toolbar: '#toolbarDemo',
                            defaultToolbar: ['exports'],
                        })
                    }

                })
            }
            // 工具栏事件
            var data;
            table.on('checkbox', function (obj) {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                data = checkStatus.data; // 获取选中的数据
                //console.log(data);
            });
            //提交关闭弹出层
            $("#demo-login").on('click', function () {
                layer.close(index);//关闭弹窗
                var selectdids = data.map(function (item) {
                    return item;
                })
                selectedRows.push(selectdids);
                console.log(selectedRows);
                ////渲染表格
                //table.render({
                //    elem: '#ID-demo',
                //    toolbar: '#toolbarDemo',
                //    cols: [[
                //        { type: 'checkbox', fixed: 'left' },
                //        { field: 'productName', width: 180, title: '产品名称' },
                //        { field: 'productCode', width: 180, title: '产品编码' },
                //        { field: 'specifications', width: 180, title: '规格' },
                //        { field: 'batch', width: 180, title: '批次' },
                //        { field: 'unit', width: 180, title: '单位' },
                //        { field: 'warehouseLocation', width: 180, title: '库位' },
                //        //{
                //        //    field: 'stockProductId', width: 195, title: '操作', templet: function (d) {
                //        //        return '<a class="layui-icon layui-icon-delete" lay-on="test-page-custom" style="color:blue" id="DelProduct" data-pandian="' + d.stockProductId + '">删除</a>'
                //        //    }
                //        //},
                //    ]],
                //    data: selectedRows
                //});
                //$.ajax({
                //    url: "/Stocktaking/SelectInventoryProduce",
                //    type: 'post',
                //    data: dto,
                //    success: function (res) {
                //        var s = JSON.parse(res);
                //        console.log(s.data);
                //        //渲染表格
                //        table.render({
                //            elem: '#ID-demo',
                //            toolbar: '#toolbarDemo',
                //            cols: [[
                //                { type: 'checkbox', fixed: 'left' },
                //                { field: 'productName', width: 180, title: '产品名称' },
                //                { field: 'productCode', width: 180, title: '产品编码' },
                //                { field: 'specifications', width: 180, title: '规格' },
                //                { field: 'batch', width: 180, title: '批次' },
                //                { field: 'unit', width: 180, title: '单位' },
                //                { field: 'warehouseLocation', width: 180, title: '库位' },
                //                //{
                //                //    field: 'stockProductId', width: 195, title: '操作', templet: function (d) {
                //                //        return '<a class="layui-icon layui-icon-delete" lay-on="test-page-custom" style="color:blue" id="DelProduct" data-pandian="' + d.stockProductId + '">删除</a>'
                //                //    }
                //                //},
                //            ]],
                //            data: s.data
                //        });

                //    }
                //})


            })
        }


    });




    var dto1 = [];
    var selected = [];
    /////查看盘点//////////////////
    var dto = {
        id: Updload,
        Token: localStorage.getItem("token")
    }
    $.ajax({
        url: "/Stocktaking/FanInventory",
        data: dto,
        type: "get",
        success: function (res) {
            var s = JSON.parse(res)
            //console.log(s.data)
            //反填
            $(s.data).each(function () {
                //console.log(this.inventoryCode)
                $("#InventoryCode").val(this.inventoryCode)
                
                $("#MorderNumber").val(this.morderNumber)
                $("#MakePerson").val(this.makePerson)


                //反填日期框
                var da = new Date(this.markTime);
                // 获取年、月、日
                var year = da.getFullYear();
                var month = (da.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                var day = da.getDate().toString().padStart(2, '0');  // 补充两位数字
                // 拼接成 "yyyy-MM-dd" 格式
                var formattedDate = `${year}-${month}-${day}`;
                $("#MarkTime").val(formattedDate)

                $("#IRremark").val(this.iRremark)
                
            })

            //添加库位下拉框
            var objs = {
                Token: localStorage.getItem("token"),
                pageIndex: 1,
                pageSize: 1000,
                StoreCode: '',
                StoreName: '',
                wid: ''
            }
            $.ajax({
                url: "/Foundation/GetStorehouse",
                type: "get",
                data: objs,
                success: function (d) {
                    var res = JSON.parse(d);
                    var supper = res.data.list;
                    //console.log(supper);
                    var options = '<option value="">请选择库位</option>';
                    supper.forEach(function (item) {
                        options += '<option value="' + item.storehouseName + '">' + item.storehouseName + '</option>';
                    });
                    $('.kw').html(options);
                    form.render('select');
                },
                error: function (xhr, status, error) {
                    console.log("新增出错: " + error);
                }
            });

            // 创建渲染实例
            table.render({
                elem: '#ID-demo',
                css: [ // 设置单元格样式
                    // 取消默认的溢出隐藏，并设置适当高度
                    '.layui-table-cell{height: 50px; line-height: 40px;}',
                    '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                    '.layui-table-cell select{height: 36px; padding: 0 5px;}'
                ].join(''),
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'productName', width: 100, title: '产品名称' },
                    { field: 'productCode', width: 100, title: '产品编码' },
                    { field: 'specifications', width: 100, title: '规格' },
                    { field: 'batch', width: 100, title: '批次', expandedMode: 'tips', edit: 'text' },
                    { field: 'warehouseLocation', width: 250, title: '库位', templet: '#TPL-select-demo' },
                    { field: 'number', width: 100, title: '库存',  },
                    { field: 'inventoryNumber', width: 100, title: '盘点数', expandedMode: 'tips', edit: 'text' },
                    
                ]],
                data: s.data[0].listProduct,
                done: function (res, curr, count) {
                    // layui form select 事件
                    form.on('select(select-demo)', function (obj) {
                        var currentDate = new Date();
                        selectedvalue = obj.value; // 获取选中项 value
                        table.on('checkbox(ID-demo)', function (obj) {
                            //当前选中的行加入到 selected 数组中
                            if (obj.checked) {
                                //console.log(obj.data) InventoryNumber
                                //console.log(selectedvalue)
                                //console.log(obj.data)
                                var a = {
                                    Number: obj.data.number,
                                    InventProductIdId: obj.data.inventProductIdId,
                                    InventoryNumber: obj.data.inventoryNumber,
                                    InventoryId: obj.data.inventoryId,
                                    ProductId: obj.data.productId,
                                    ProductName: obj.data.productName,
                                    ProductCode: obj.data.productCode,
                                    Specifications: obj.data.specifications,
                                    Batch: obj.data.batch,
                                    Unit: obj.data.unit,
                                    WarehouseLocation: selectedvalue,
                                    office_id: "1",
                                    user_id: 1,
                                    addName: "卢芳",
                                    addTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
                                    updName: "朱柏霖",
                                    updTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
                                }
                                dto1.push(a);
                            }
                            else {
                                // 当前取消选中的行从 selected 数组中移除
                                selected = selected.filter(row => row.productsID !== obj.data.productsID);
                            }
                        })
                    });
                    // 单元格普通编辑事件
                    table.on('edit(ID-demo)', function (obj) {
                        var value = obj.value // 得到修改后的值
                        var data = obj.data // 得到所在行所有键值
                        var field = obj.field; // 得到字段
                    });
                }
            });


        }
    })



    /////上传////////////////////////////////////////
    $("#Uploadd").on('click', function () {

        var currentDate = new Date();
        var dto = {
            InventoryId:localStorage.getItem("UploadID"),
            inventoryCode: $("#InventoryCode").val(),
            morderNumber: $("#MorderNumber").val(),
            makePerson: $("#MakePerson").val(),
            markTime: $("#MarkTime").val(),
            iRremark: $("#IRremark").val(),
            inventoryState: 1,
            inventoryType: "产品盘点",
            office_id: "1",
            user_id: 1,
            addName: "卢芳",
            addTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
           updName: "朱柏霖",
            updTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
            UpdInventGuan: dto1,
            Token: localStorage.getItem("token")
        };
        console.log(dto)
        //return false;
        $.ajax({
            url: "/Stocktaking/UpdStockings",
            type: 'post',
            data: dto,
            success: function (res) {
                var s = JSON.parse(res);
                if (s.data == 1) {
                    layer.msg('上传成功', { icon: 0 }, function () {
                        //location.reload()
                        location.href = "/Stocktaking/Stocking";
                    });
                }
                else if (s.data == -1) {
                    layer.msg('类别名称已存在，不能上传');
                    return
                }
                else {
                    layer.msg('上传失败');
                    return
                }
            }
        })

        //var currentDate = new Date();
        //// 生成6位数
        //var randomNum = Math.floor(100000 + Math.random() * 900000);  // 生成100000到999999之间的随机整数
        //var dto = {

        //    inventoryCode: randomNum,
        //    morderNumber: $("#MorderNumber").val(),
        //    makePerson: $("#MakePerson").val(),
        //    markTime: $("#MarkTime").val(),
        //    iRremark: $("#IRremark").val(),
        //    inventoryState: 1,
        //    inventoryType: "产品盘点",
        //    office_id: "1",
        //    user_id: 1,
        //    addName: "卢芳",
        //    addTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
        //    addInventGuan: selectdids,
        //    Token: localStorage.getItem("token")
        //};
        //console.log(dto);
        //$.ajax({
        //    url: "/Stocktaking/ADDStockings",
        //    type: 'post',
        //    data: dto,
        //    success: function (res) {
        //        var s = JSON.parse(res);
        //        if (s.data == 1) {
        //            layer.msg('添加成功', { icon: 0 }, function () {
        //                location.reload()
        //            });
        //        }
        //        else if (s.data == -1) {
        //            layer.msg('类别名称已存在，不能添加');
        //            return
        //        }
        //        else {
        //            layer.msg('添加失败');
        //            return
        //        }
        //    }
        //})



    })
});